local Pca9545 = {}

ADDR_IDX = 1
ADDR_MASK = 0xFE
CONTROL_IDX = 2
CHANNEL_MASK = 0x0F

local function parse_addr(tx_buffer)
    return tx_buffer[ADDR_IDX] & ADDR_MASK
end

local function parse_channel(tx_buffer)
    local channel_state = {}
    if #tx_buffer ~= 2 then -- 2: 9545接收接收命令的长度
        print("command len fail, len=", #tx_buffer)
        return channel_state
    end
    local control = tx_buffer[CONTROL_IDX]
    local channel = control & CHANNEL_MASK
    while channel ~= 0 do
        local b_set = channel & 0x01
        table.insert(channel_state, b_set)
        channel = channel >> 1
    end
    return channel_state
end

function Pca9545.write(tx_buffer)
    local addr = parse_addr(tx_buffer)
    local channel_state = parse_channel(tx_buffer)
    local channel_path = ""
    for i = 1, #channel_state do
        if channel_state[i] == 1 then
            channel_path = string.format("/0x%02x/%d", addr, i - 1)
            break
        end
    end
    local t = {}
    t["hub"] = channel_path
    return t
end

return Pca9545
